<template>
  <div>
      <div class="head border-bottom-1px">
          <div class="left" @click="showPicker">
              {{this.$store.state.address_info.city}}
              <i class="address_dw_icon" :style="address_dw_icon"></i>
          </div>

          <div class="f1">
              <i class="adress_icon" :style="adress_icon" ></i>
              <cube-input
                  v-model="shiming.value"
                  :placeholder="shiming.placeholder"
                  :type="shiming.type"
                  :maxlength="shiming.maxlength"
                  :readonly="shiming.readonly"
                  :disabled="shiming.disabled"
                  :autofocus="shiming.autofocus"
                  :autocomplete="shiming.autocomplete"
                  :eye="shiming.eye"
                  :clearable="shiming.clearable"
                  v-on:input="serach_address"
                ></cube-input>
          </div>
          <div class="serach_address_txt" @click="serach_address()">
              <p>搜索</p>
          </div>
      </div>
      <!-- <cube-button icon="cubeic-location" :class="{button_hide : is_normal}" @click="serach_address_location">微信一键获取当前定位</cube-button> -->
      <div class="again" v-if="!is_normal" @click="get_wexin_lat">
          <p>重新定位</p>
          <i class="again_icon" :style="again_icon"></i>
      </div>
      <div class="wrapper">
          <div class="list">
              <ul>
                  <li class="border-bottom-1px" v-for="(val,key) in result_list" @click="btn_address(key)">
                      <p class="address_name">{{val.name}}</p>
                      <p class="address_txt">{{val.address}}</p>
                      <i class="address_icon" :style="address_icon"></i>
                  </li>
              </ul>
          </div>
      </div>
      <p v-if="is_nodizhi" style="margin-top: 2rem;font-size: .56rem;">搜索不到您的地理位置</p>
  </div>
</template>
<script>
import wx from 'weixin-js-sdk';
export default {
    data(){
        return{
            adress_icon:{
                backgroundImage: "url(" + require("../assets/index_search@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            address_dw_icon:{
                backgroundImage: "url(" + require("../assets/address_dw_icon@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            run_icon:{
                backgroundImage: "url(" + require("../assets/label_back@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            again_icon:{
                backgroundImage: "url(" + require("../assets/position_refresh@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            address_icon:{
                backgroundImage: "url(" + require("../assets/position_l@2x.png") + ")",
                backgroundRepeat: "no-repeat",
                backgroundSize: "cover"
            },
            selectedIndex:[],
            address_data:[],
            is_nodizhi:false,//false不显示搜索不到地址提醒
            is_normal:false,//false表示是微信浏览器
            result_list:[],
            shiming:{
                value: this.$store.state.address_info.address,
                placeholder: '街道/区/大厦/等',
                type: 'text',
                readonly: false,
                maxlength: 100,
                disabled: false,
                autofocus: true,
                autocomplete: true,
                // eye: {
                //     open: true,
                //     reverse: false
                // },
                clearable:{
                    visible: true,
                    blurHidden: true
                }
            },

        }
    },
    metaInfo: {
      title: "请选择所在地区"
    },
    methods:{
      showPicker() {
        if (!this.picker) {
          this.picker = this.$createCascadePicker({
            title: '请选择所在地区',
            data: this.address_data,
            onSelect: this.selectHandle,
            onCancel: this.cancelHandle
          })
        }
        this.picker.show()
      },
      selectHandle(selectedVal, selectedIndex, selectedText) {
        console.log(selectedVal);
        console.log(selectedText);
        this.$store.state.address_info.province = selectedText[0];
        this.$store.state.address_info.city = selectedText[1];
        this.$store.state.address_info.province_id = selectedVal[0];
        this.$store.state.address_info.city_id = selectedVal[1];
        if(!this.isInArray([1,2,9,22,35],selectedVal[0])){
            this.$store.state.address_info.area = selectedText[2];
            this.$store.state.address_info.area_id = selectedVal[2];
        }else{
            this.$store.state.address_info.area = "";
            this.$store.state.address_info.area_id = 0;
        }
        console.log(this.$store.state.address_info);
        // this.$createDialog({
        //   type: 'warn',
        //   content: `Selected Item: <br/> - value: ${selectedVal.join(', ')} <br/> - index: ${selectedIndex.join(', ')} <br/> - text: ${selectedText.join(' ')}`,
        //   icon: 'cubeic-alert'
        // }).show()
      },
      cancelHandle() {
        // this.$createToast({
        //   type: 'correct',
        //   txt: 'Picker canceled',
        //   time: 1000
        // }).show()
      },
      isInArray:function(arr,value){
           if(arr.indexOf&&typeof(arr.indexOf)=='function'){
                var index = arr.indexOf(value);
                if(index >= 0){
                    return true;
                }
            }
            return false;
      },
      serach_address(){
        let that = this;
        this.$store.state.address_info.address = this.shiming.value;
        let pdata = this.$store.state.address_info;
        pdata.access_token = this.$store.state._token01;
        let url = this.$store.state.host+"/fang/store/get_address";
        this.$axios.post(url,that.$qs.stringify(pdata))
        .then(function(response){
            let res = response.data;
            if(res.data.length == 0){
                that.is_nodizhi = true;
            }else{
                that.is_nodizhi = false;
            }
            that.result_list = res.data;
        })
        .catch(function(error){
            console.log(error);
        });
      },
      serach_address_location(lat,lng){
            let that = this;
            // if(!this.$store.state.latitude && !this.$store.state.longitude){
            //     let lat = '22.72402';
            //     let lng = '114.260671';
            // }else{
            //     let lat = this.$store.state.latitude;
            //     let lng = this.$store.state.longitude;
            // }

            this.$store.state.address_info.address = this.shiming.value;
            let pdata = that.$qs.stringify({lat:lat,lng:lng});
            let url = this.$store.state.host+"/fang/store/get_address_location";
            console.log(pdata);
            this.$axios.post(url,pdata)
            .then(function(response){
                let res = response.data;
                that.result_list = res.data;
            })
            .catch(function(error){
                console.log(error);
            });
        },
        get_wexin_lat(){
            let that = this;
            const toast = that.$createToast({
                time: 8000,
                txt: ''
             })
             toast.show()
            wx.getLocation({
                 type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                 success: function (res) {
                    console.log(res,"res");
                     var latitude = parseFloat(res.latitude); // 纬度，浮点数，范围为90 ~ -90
                     var longitude = parseFloat(res.longitude); // 经度，浮点数，范围为180 ~ -180。
                     var speed = res.speed; // 速度，以米/每秒计
                     var accuracy = res.accuracy; // 位置精度
                     // wgs84 转百度
                     let bd09 = that.$options.methods.wgs84togcj02tobd09(longitude,latitude)
                     that.serach_address_location(bd09.lat,bd09.lng)
                 },
                 fail: function(res){
                     console.log(res,"fail");
                     setTimeout(function(){
                         const toastlog = that.$createToast({
                             time: 2000,
                           txt: "定位失败了,打开GPS定位试试",
                           type: 'txt'
                         })
                         toastlog.show()
                     },500)
                     // that.serach_address_location(that.$store.state.latitude,that.$store.state.longitude);
                 },
                 complete:function(res){
                      toast.hide();
                 },
                 cancel: function (res) {
                      // alert('用户拒绝授权获取地理位置');
                      // that.serach_address_location(that.$store.state.latitude,that.$store.state.longitude);
                  }
            });
        },
        /**
        * WGS84转GCj02
        * 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
        */
       wgs84togcj02tobd09 (lng, lat) {
             const xPI = 3.14159265358979324 * 3000.0 / 180.0
             const PI = 3.1415926535897932384626
             const a = 6378245.0
             const ee = 0.00669342162296594323
             // WGS84转GCj02
             let dlat = this.transformlat(lng - 105.0, lat - 35.0)
             let dlng = this.transformlng(lng - 105.0, lat - 35.0)
             let radlat = lat / 180.0 * PI
             let magic = Math.sin(radlat)
             magic = 1 - ee * magic * magic
             let sqrtmagic = Math.sqrt(magic)
             dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI)
             dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI)
             let mglat = lat + dlat
             let mglng = lng + dlng
             // 火星坐标系 (GCJ-02) 与百度坐标系 (BD-09) 的转换
             let z = Math.sqrt(mglng * mglng + mglat * mglat) + 0.00002 * Math.sin(mglat * xPI)
             let theta = Math.atan2(mglat, mglng) + 0.000003 * Math.cos(mglng * xPI)
             let bdlng = z * Math.cos(theta) + 0.0065
             let bdlat = z * Math.sin(theta) + 0.006
             // return [bdlng, bdlat]
             return {lng: bdlng, lat: bdlat}
           },
           transformlat (lng, lat) {
             const PI = 3.1415926535897932384626
             let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng))
             ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
             ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0
             ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0
             return ret
           },
           transformlng (lng, lat) {
             const PI = 3.1415926535897932384626
             let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng))
             ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0
             ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0
             ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0
             return ret
         },
        btn_address(key){
            let result_list = this.result_list[key];
            console.log(result_list)
            if(typeof(result_list.location) == "undefined" && typeof(result_list.location) == "undefined"){
                this.toast = this.$createToast({
                  txt: "请输入更详细的地址，以便提供更好的服务",
                  type: 'txt'
                })
                this.toast.show()
                return;
            }
            this.$store.state.latitude = result_list.location.lat;
            this.$store.state.longitude = result_list.location.lng;
            this.$store.state.address_status = result_list.name;
            //存cookies bd09 = 转换后的经纬度和地址名字
            let bd09_name = {
                latitude:result_list.location.lat,
                longitude:result_list.location.lng,
                address_status:result_list.name
            }
            this.$store.commit('setLocation',bd09_name);
            if(this.$cookies.isKey('bd09_name')){
                this.$cookies.remove('bd09_name','/','.01nnt.com');
            }
            this.$cookies.set("bd09_name",bd09_name,"2h");
            //本应该跳转index,但是由于没有用户信息进入中间页面author,再跳转到index就获取不到params,所以只能跳转author
            //在author中判断
            this.$router.push({ name: 'index', params: { latitude: result_list.location.lat, longitude:result_list.location.lng}})
        }
    },
    components:{

    },
    mounted:function(){
      let that = this;
      document.getElementsByTagName("body")[0].className="address_active_bg";

      if (/MicroMessenger/.test(window.navigator.userAgent)) {
          this.is_normal = false;
      } else {
          this.is_normal = true;
      }
      let url = "/fang/store/get_p_c_a";
      this.$axios({
          url:url,
          method:"get",
          responseType:"json",
      })
      .then(function(response){
          console.log(response);
          let res = response.data;
          if(res.status == 1){
            that.address_data = res.data;
          }
      })
      .catch(function(error){
          console.log(error);
      });
    },
    beforeCreate:function(){
        document.getElementsByTagName("body")[0].className="address_active_bg";
        let that = this;
        // wx.ready(function () {
        //     that.get_wexin_lat();
        // })

    },
    activated:function(){
      //使用keep-alive以后进入页面只会触发activated
      document.getElementsByTagName("body")[0].className="address_active_bg";
      let that = this;
      wx.ready(function () {
          that.get_wexin_lat();
      })

      document.getElementsByTagName("body")[0].className="address_active_bg";

      if (/MicroMessenger/.test(window.navigator.userAgent)) {
          this.is_normal = false;
      } else {
          this.is_normal = true;
      }
      let url = "/fang/store/get_p_c_a";
      // this.$axios.get(url,{
      //       access_token:this.$store.state._token01
      // })
      this.$axios({
          url:url,
          method:"get",
          responseType:"json",
      })
      .then(function(response){
          console.log(response);
          let res = response.data;
          if(res.status == 1){
            that.address_data = res.data;
          }
      })
      .catch(function(error){
          console.log(error);
      });
    },
    beforeDestroy: function() {
        document.body.removeAttribute("class","address_active_bg");
    },
    deactivated:function(){
        //deactivated使用keep-alive以后推出页面只会触发deactivated
        document.body.removeAttribute("class","address_active_bg");
    }
}
</script>
<style scoped>
.head{
    height: 1.86rem;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #FFFFFF;
}
.border-bottom-1px::after{
    border-bottom-color: #E0E0E0;
}
.head .left{
    width: 2.5rem;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.head .left .address_dw_icon{
    width: .36rem;
    height: .24rem;
    display: inline-block;
    margin:  0 .2rem;
}
.head .f1{
    flex: 1;
    position: relative;
    z-index: 1;
}
.cube-input{
    border: 1px solid rgba(229,229,229,1);
    box-shadow: 0 0.6rem 0.4rem -0.4rem rgba(238,238,238,0.5);
    /* margin-right: 2rem; */
    padding-left: 1.04rem;
}
.cube-input::after{
    border: none;
}
.serach_address_txt{
    width: 2rem;
    width: 2rem;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}
.adress_icon{
    display: block;
    height: .52rem;
    width: .52rem;
    position: absolute;
    left: .3rem;
    top: 50%;
    transform: translate(0,-50%);
    z-index: 2;
}
.run_icon{
    display: block;
    height: .68rem;
    width: .38rem;
    margin-left: .44rem;
}
.again{
    height: 1.98rem;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding: 0 .64rem;
    font-size: .56rem;
    color: #333333;
}
.again .again_icon{
    width: .56rem;
    height: .56rem;
}
.wrapper{
    background: #FFFFFF;
    border-top-left-radius: .8rem;
    border-top-right-radius: .8rem;
}
.wrapper .list{
    padding:.0 .64rem 0 .64rem;
}
.wrapper .list ul li{
    padding-right: 2.1rem;
    text-align: left;
    position: relative;
    padding: .68rem 1rem .74rem 0;
}
.wrapper .list ul li .address_name{
    font-size: .56rem;
    color: #333333;
    font-weight: 500;
    margin-bottom: .76rem;
}
.wrapper .list ul li .address_txt{
    color: #999999;
    overflow: hidden;
     text-overflow: ellipsis;
     display: -webkit-box;
     -webkit-line-clamp: 2;
     -webkit-box-orient: vertical;
     line-height: 1.2;
}
.wrapper .list ul li .address_icon{
    width: .56rem;
    height: .68rem;
    position: absolute;
    right: .16rem;
    top: 50%;
    transform: translate(0,-50%);
}
.wrapper .list ul .border-bottom-1px::after{
    border-bottom-color: #F5F5F5;
}
.button_hide{
  display: none;
}
</style>
<style lang="stylus" rel="stylesheet/stylus">
    .f1
        .cube-input-field
            padding: 0 !important
  .cube-input
    height: 1.16rem;

</style>
